#/* @file         my_script.sh
#*  @author       Schips
#*  @copyright    Copyright By Schips, All Rights Reserved
#*/

#!/bin/sh

# 如果需要看到 过程，则 在使用时随便提供一个参数
export SHVERBOSE=$1
echo 'Using [myScript]'

# getArg0
if [ -z "${BASH_SOURCE[0]}" ]; then
#as zsh
A0=$0
else
#as bash
A0=${BASH_SOURCE[0]}
fi

export MYSC_ROOT_DIR=`dirname $A0`
export MYSC_CONFIG_ROOT=$HOME/.config/mysc/
export MYSC_CONFIG=$MYSC_CONFIG_ROOT/config
export THIS_SH=`basename $A0`

# 初始化
mysc_init () {
    # 不允许 有脚本与 my_script.sh 重名
    # 放在 .todo, .ref 目录下的文件不会被执行
    # 打印时，不打印前2个字符: './'
    for sh_file in `cd $MYSC_ROOT_DIR; find . -type f -name "*.sh" | grep -v "$THIS_SH" | grep -v ".todo/" | grep -v ".ref/" | sed 's/..//'`
    do
        source $MYSC_ROOT_DIR/$sh_file

        if [ ! -z "$SHVERBOSE" ]; then
            echo "Source $sh_file"
        fi

    done
}

###################### CORE , DO NOT EDIT ######################
# 快速 跳转到 所在目录
function mysc-root () {
    cd $MYSC_ROOT_DIR
}
alias mysc='mysc-root'

# 重新加载配置
function mysc-reload () {
    source $MYSC_ROOT_DIR/$THIS_SH
}
alias reload='mysc-reload'

function require () {
    echo "Checking [$1]"
    command -v $1 >/dev/null 2>&1 || { echo >&2 "Aborted : Require \"$1\" but not found."; return 255; }
	return 0
}

function get_mysc_root_dir () {
    echo $MYSC_ROOT_DIR
}

function mysc-cfg-set () {
# 内部命令
    local cfg_var_name=$1
    local cfg_var_value=$2
    if [ -z "$1" ]; then
    	return 1
	fi
    if [ -z "$2" ]; then
    	return 1
	fi
    if [ ! -f "$MYSC_CONFIG" ]; then
        mkdir -p `dirname $MYSC_CONFIG`
        echo "export $cfg_var_name=$cfg_var_value" >> $MYSC_CONFIG
        echo "[A] $cfg_var_name=$cfg_var_value"
		return 0
	fi

    # 如果使用到了'$'但不是'\$',那么需要告诉用户进行手动转义（因为在sed中会有bug）
    local escape_check=`echo "$cfg_var_value" | grep -F '$'`
    if [ ! -z "$escape_check" ];then
        escape_check=`echo "$cfg_var_value" |  grep -F "\\\\$"`
        if [ -z "$escape_check" ];then
            echo "To use '\$', please replace it as '\\\$'"
            return 1
        fi
    fi

    # 从 配置中查看是否有此行
    local result=`cat $MYSC_CONFIG | grep $cfg_var_name | grep export | grep -v \#`
    if [ -z "$result" ]; then
        echo "[A] $cfg_var_name=$cfg_var_value"
        echo "export $cfg_var_name=$cfg_var_value" >> $MYSC_CONFIG
    else
        bash <<EOF
sed -i 's#^export.*$cfg_var_name=.*#export $cfg_var_name=$cfg_var_value#g' $MYSC_CONFIG
EOF
        if [ "$?" -eq 0 ]; then
            echo "[M] $cfg_var_name=$cfg_var_value"
        else
            echo "[X] failed!"
        fi
	fi
}

function mysc-cfg-get () {
    local cfg_var_name=$1
    if [ -z "$1" ]; then
    	return 1
	fi
    if [ ! -f "$MYSC_CONFIG" ]; then
	    mkdir -p `basename $MYSC_CONFIG`
	    touch $MYSC_CONFIG
		return 1
	fi
    local result=`cat $MYSC_CONFIG | grep -w $cfg_var_name | grep 'export' | grep -v \# | head -n 1`
    if [ -z "$result" ]; then
		return 0
	fi
	echo $result | awk -F\= '{print$2}'
}

function mysc-changeCmd() {
    local COMMAMD=$1
    if [ -z "$COMMAMD" ]; then
    	return 0
	fi

    local ROOT_DIR=`get_mysc_root_dir`
    if [ -z "$ROOT_DIR" ]; then
    	return 1
	fi

    # 要求函数名 必须是以 function 或者 alias 定义的
    local find_result=`grep -w $COMMAMD $ROOT_DIR -nR | grep -E 'function|alias'| head -n 1`
    if [ -z "$find_result" ]; then
    	return 1
	fi
    local editor=`mysc-cfg-get-editor`
    local editor_can_jmp_line=`mysc-cfg-get editor_can_jmp_line`
	local cmd_in_file=`echo $find_result | awk -F: '{print$1}'`
    #echo editor=$editor
    #echo editor_can_jmp_line=$editor_can_jmp_line
    #echo cmd_in_file=$cmd_in_file
    if [ -z "$cmd_in_file" ]; then
    	return 1
	fi
    if [ -z "$editor" ]; then
        echo "USE mysc-cfg-set"
        return 1
	fi

    if [ ! "$editor_can_jmp_line" = "1" ]; then
        `echo $editor` $cmd_in_file
    else
	    local cmd_in_file_line=`echo $find_result | awk -F: '{print$2}'`
        `echo $editor` $cmd_in_file  +$cmd_in_file_line
	fi
}

function mysc-cfg-set-editor ()
{
    ## 批量执行
    local edBin=""
    loopvar="$1"
    while [ true ];
    do
	if command -v $loopvar >/dev/null 2>&1; then
            mysc-cfg-set editor $loopvar
            return 0
	fi
        shift
	loopvar="$1"
    done
    echo "Warning : not editor found!"
    return 1
}

# 从远程仓库进行更新
function mysc-update ()
{
    bash <<EOF
    cd $MYSC_ROOT_DIR
    git pull
EOF
    mysc-reload
}

# 从远程仓库进行强制更新
function mysc-update-force ()
{
    bash <<EOF
    cd $MYSC_ROOT_DIR
    git pull --force origin master:master
EOF
    mysc-reload
}

function mysc-cfg-get-editor ()
{
    local MY_EDITOR=`mysc-cfg-get editor`
    if [ ! -f "$MY_EDITOR" ]; then
        mysc-cfg-set-editor /usr/bin/nvim /usr/bin/vim /bin/nano > /dev/null
    fi
    mysc-cfg-get editor
}

function mysc-initMyscConfig () {

    mkdir -p `dirname $MYSC_CONFIG`
    echo "* Init defalut config for myScript *"

    if [ -f "$MYSC_CONFIG" ]; then
		cp $MYSC_CONFIG $MYSC_CONFIG.bak
        rm $MYSC_CONFIG
	fi
    touch $MYSC_CONFIG

    # 设置编辑器 为 nvim
    mysc-cfg-set-editor /usr/bin/nvim /usr/bin/vim
    # 设置 编辑器 在编辑时可以跳转到指定行
    mysc-cfg-set editor_can_jmp_line 1
    # 设置 用户名，邮箱，可用于git
    mysc-cfg-set author schips
    mysc-cfg-set email  schips@dingtalk.com
    # 设置 远程服务器有关地址，此后可以使用对应的命令进行登录
    mysc-cfg-set snet  192.168.1
    mysc-cfg-set sip 1
    mysc-cfg-set host  schips
    #cat $MYSC_CONFIG
}

if [ ! -d "$MYSC_CONFIG_ROOT" ]; then
    mkdir -p $MYSC_CONFIG_ROOT
fi
if [ ! -f "$MYSC_CONFIG" ]; then
    mysc-initMyscConfig
fi
mysc_init
